/*
 * @lc app=leetcode.cn id=331 lang=javascript
 *
 * [331] 验证二叉树的前序序列化
 */

// @lc code=start
/**
 * @param {string} preorder
 * @return {boolean}
 */
var isValidSerialization = function(preorder) {
  const preorderList = preorder.split(',');
  const l = preorderList.length;
  const stack = [1];
  let i = 0;
  while(i < l) {
      if (!stack.length) return false;
      if (preorderList[i] === '#') {
          stack[stack.length - 1]--;
          if (stack[stack.length - 1] === 0) {
              stack.pop();
          }
          i++;
      } else {
          stack[stack.length - 1]--;
          if (stack[stack.length - 1] === 0) {
              stack.pop();
          }
          stack.push(2);
          i++;
      }
  }
  return !stack.length;
};
// @lc code=end

